package com.yjd.bi.etl.user.service;

import java.util.Calendar;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.yjd.bi.etl.comm.BaseService;
import com.yjd.bi.etl.comm.Constants;
import com.yjd.bi.etl.sql.UserSqlConstants;
import com.yjd.bi.report.model.BiDatabaseInfoModel;
import com.yjd.bi.report.util.BiUtil;
import com.yjd.comm.util.DateUtil;

@Component("userStatisticConditionService")
public class UserStatisticConditionService extends BaseService {

	private static final int  DAYOFSECOND = 86400;

	public void statisticEveryDayData() throws Exception {

		BiDatabaseInfoModel model = this.getBiDatabaseInfoModel();
		JdbcTemplate jt = BiUtil.getJdbcTemplate(model);

		// 统计历史数据
		long maxDate = jt.queryForInt(UserSqlConstants.GET_MAX_USERSTATISTIC_DATE_CONDITION);
		
		if (maxDate == 0) {
			// 没有统计过，取网站上线运营的第一天 平台上线时间（2013年12月21日00：00：00）
			maxDate = Constants.INITIALIZATION_TIME;
		}else{
			maxDate = DateUtil.dateStringToTimestamp(maxDate+"",
					DateUtil.PATTERN_yyyyMMdd)+DAYOFSECOND;
		}
		
		//获取当天的0点的时间戳
		Calendar todayStart = Calendar.getInstance();  
        todayStart.set(Calendar.HOUR_OF_DAY, 0);  
        todayStart.set(Calendar.MINUTE, 0);  
        todayStart.set(Calendar.SECOND, 0);  
        todayStart.set(Calendar.MILLISECOND, 0);
        long todayTime = todayStart.getTime().getTime()/1000L; 
		
		while (maxDate  < todayTime ) {
			// 统计前一天的用户数据
			statisticLastData(maxDate, jt,1);
			statisticLastData(maxDate, jt,2);
			maxDate += DAYOFSECOND;// 加一天和当前时间比较，如果小于当前时间则继续统计
			
		}
	}

	/**
	 * 统计某天前一天的用户数据
	 */
	private void statisticLastData(long maxDate, JdbcTemplate jt,int sex)
			throws Exception {

		long beginDate = maxDate;
		long endDate = beginDate + DAYOFSECOND - 1;

		// 注册用户数
		int registerCount = jt.queryForInt(UserSqlConstants.REGISTERCOUNTSQL_CONDITION,sex, beginDate, endDate);

		// 登录用户数
		int loginCount = jt.queryForInt(UserSqlConstants.LOGINCOUNTSQL_CONDITION, beginDate, endDate,sex);

		// 充值用户数
		int rechargeCount = jt.queryForInt(UserSqlConstants.RECHARGECOUNTSQL_CONDITION, beginDate, endDate,sex);

		// 投资用户数
		int investCount = jt.queryForInt(UserSqlConstants.INVESTCOUNTSQL_CONDITION, beginDate, endDate, beginDate, endDate, beginDate, endDate,sex);
		
		Long staticsDate = Long.parseLong(DateUtil.timestampToDateString(
				beginDate, DateUtil.PATTERN_yyyyMMdd));
		
		logger.info("beginDate:"+beginDate+",registerCount:"+registerCount+",loginCount:"+loginCount+",rechargeCount:"+rechargeCount+",investCount:"+investCount);
		
		jt.update(UserSqlConstants.USERSTATISTIC_INSERTSQL_CONDITION,staticsDate,registerCount,loginCount,rechargeCount,investCount,sex);

	}
}
